import store from '@/store/index.js';
import config from '../config.js';
import handle from '@/common/messageHandler.js'
import {sub} from '@/common/event.js'
let socketOpen = false;
let socketMsgQueue = [];
let st;
let stping;

sub("logout",function(){
	uni.closeSocket({
		success() {
			console.log("消息中心-sub关闭")
		}
	})
})

uni.connectSocket({
	url: config.webSocketUrl,
});
uni.onSocketOpen(function(res) {
	console.log(`websocket 已连接`,res)
	socketOpen = true;
	store.commit(`websocket/setConnectState`,true)
	clearInterval(st)
	st = null
	stping = setInterval(()=>{
		sendSocketMessage({
			type:"ping",
			data:{}
		})
	},10000)
	for (var i = 0; i < socketMsgQueue.length; i++) {
		sendSocketMessage(socketMsgQueue[i]);
	}
	socketMsgQueue = [];
});

uni.onSocketError(function(res) {
	console.log('WebSocket 出错！');
	uni.closeSocket()
	socketOpen = false
	store.commit(`websocket/setConnectState`,false)
	if(stping){
		clearInterval(stping)
		stping = null
	}
	if(st) return
	// 尝试重连
	st = setInterval(() => {
		console.log('WebSocket 尝试链接或重连！');
		if(socketOpen){
			clearInterval(st)
			st = null
			return
		}
		uni.connectSocket({
			url: config.webSocketUrl,
		});
	}, 5000)
});

uni.onSocketClose(function(res) {
	console.log('WebSocket 已关闭！');
	socketOpen = false
	store.commit(`websocket/setConnectState`,false)
	if(st) return
	// 尝试重连
	st = setInterval(() => {
		console.log('WebSocket 尝试链接或重连！');
		if(socketOpen){
			clearInterval(st)
			st = null
			return
		}
		uni.connectSocket({
			url: config.webSocketUrl
		});
	}, 5000)
});

function sendSocketMessage(msg) {
	if(store.state.user.user.id){
		msg.user = {
			id:store.state.user.user.id,
			name:store.state.user.user.name,
			avatar:store.state.user.user.avatar
		}
	}
	if (socketOpen) {
		uni.sendSocketMessage({
			data: JSON.stringify(msg)
		});
	} else {
		socketMsgQueue.push(msg);
	}
}


uni.onSocketMessage(function(res) {
	// console.log('收到服务器内容：', res);
	const message = res.data
	handle.handle(JSON.parse(message))
});

module.exports = {
	send: sendSocketMessage,
}